<template>
  <ContentWrap v-loading="formLoading">
    <el-tabs v-model="activeName">
      <el-tab-pane label="商品权限" name="permission">
        <PermissionForm
          ref="permissionRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <el-tab-pane label="营销设置" name="promotion">
        <PromotionForm
          ref="promotionRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <el-tab-pane label="会员折扣" name="vipDiscounts">
        <VipDiscountsForm
          ref="vipDiscountsRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <el-tab-pane label="佣金设置" name="brokerage">
        <BrokerageForm
          ref="brokerageRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
    </el-tabs>
    <el-form>
      <el-form-item style="float: right">
        <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as ProductSpuApi from '@/api/mall/product/spu'

import PermissionForm from './PermissionForm.vue'
import PromotionForm from './PromotionForm.vue'
import VipDiscountsForm from './VipDiscountsForm.vue'
import BrokerageForm from './BrokerageForm.vue'
import { convertToInteger, floatToFixed2, formatToFraction } from '@/utils'

defineOptions({ name: 'ProductSpuAdd' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('permission') // Tag 激活的窗口
const isDetail = ref(false) // 是否查看详情

const permissionRef = ref() //商品权限 Ref
const promotionRef = ref() //营销设置 Ref
const vipDiscountsRef = ref() //会员折扣 Ref
// const protocolRef = ref() //商品协议 Ref
const brokerageRef = ref() //佣金设置
const otherRef = ref() // 其他设置 Ref
// SPU 表单数据
const formData = ref<ProductSpuApi.Spu>({
  spuType: 1,
  spuId: undefined,
  spuName: '', //商品名称
  titleName: '', // 商品标题(商城)
  subTitleName: '', //商品副标题
  categoryId: undefined, // 线上商品分类
  categoryStoreId: undefined, //门店商品分类
  keyword: '', // 关键字
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图
  introduction: '', // 商品简介
  deliveryTypes: [], // 配送方式数组
  deliveryTemplateId: undefined, // 运费模版
  brandId: undefined, // 商品品牌
  specType: false, // 商品规格
  subCommissionType: false, // 分销类型
  skus: [
    {
      price: 0, // 商品价格
      marketPrice: 0, // 市场价
      costPrice: 0, // 成本价
      barCode: '', // 商品条码
      picUrl: '', // 图片地址
      stock: undefined, // 库存
      weight: 0, // 商品重量
      volume: 0, // 商品体积
      firstBrokeragePrice: 0, // 一级分销的佣金
      secondBrokeragePrice: 0, // 二级分销的佣金
      giveGoods: [] as any, //关联商品
      lowPrice: 0, //最低价
      usableTimes: undefined, //可用次数
      merchantCode: '', //商家编码
      unit: '', //商品单位
      skuType: undefined //商品属性
    }
  ],
  description: '', // 商品详情
  sort: 0, // 商品排序
  giveIntegral: 0, // 赠送积分
  virtualSalesCount: 0, // 线下销量
  salesChannel: [], //销售渠道
  spuTags: '', // 商品标签
  spuColor: '#ff0000', // 商品标签颜色
  imgOblongUrl: '', //商品主图2 长方形
  imgScale: 0, //图片视频比例  1:1、3:4、4:3、16:9
  isVideo: false, //是否有视频文件
  videoImg: '', //视频封面
  videoUrl: '', //视频链接
  videoAutoplay: false, //自动播放
  videoMuteplay: false, //禁音播放
  tenantNumType: 0, //销售门店类型 0全部 1部分
  authorizedTenant: [], //销售门店
  tenantServiceNumType: 0, //服务门店类型 0全部 1部分
  authorizedServiceTenant: [], //服务门店
  salesOnlineChannel: [], // 线上商品销售渠道
  freightSet: 2, //运费设置 1固定运费 2运费模板
  freight: 0, //固定运费
  productUp: 0, //商品上架类型
  productUpTime: '', //商品上架时间
  productDown: 0, //商品下架类型
  productDownTime: '' // 商品下架时间

  // quotaAuthority: {
  //   selectId: 1
  // },
  // memberIntegral: {
  //   selectId: 0,
  //   ruleList: []
  // }, //会员积分设置
  // paidmemberIntegral: {
  //   selectId: 0,
  //   ruleList: []
  // }, //付费会员积分设置
  // deduMemberIntegral: {
  //   selectId: 0,
  //   ruleList: []
  // },
  // deduPaidmemberIntegral: {
  //   selectId: 0,
  //   ruleList: []
  // },
  // memberBalance: {
  //   selectId: 0,
  //   ruleList: []
  // },
  // paidmemberBalance: {
  //   selectId: 0,
  //   ruleList: []
  // }
})

/** 获得详情 */
const getDetail = async () => {
  if ('ProductSpuDetail' === name) {
    isDetail.value = true
  }
  const spuId = params.spuId as unknown as number
  if (spuId) {
    formLoading.value = true
    try {
      const res = (await ProductSpuApi.getSpu(spuId)) as ProductSpuApi.Spu
      if (isDetail.value) {
        res.freight = floatToFixed2(res.freight)
      } else {
        // 固定运费回显价格分转元
        res.freight = formatToFraction(res.freight)
      }
      console.log(res)

      res.skus?.forEach((item) => {
        if (isDetail.value) {
          item.price = floatToFixed2(item.price)
          item.marketPrice = floatToFixed2(item.marketPrice)
          item.costPrice = floatToFixed2(item.costPrice)
          item.lowPrice = floatToFixed2(item.lowPrice)
        } else {
          // 回显价格分转元
          item.price = formatToFraction(item.price)
          item.marketPrice = formatToFraction(item.marketPrice)
          item.costPrice = formatToFraction(item.costPrice)
          item.lowPrice = formatToFraction(item.lowPrice)
        }
      })
      formData.value = res
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交按钮 */
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    // 校验各表单

    // await unref(permissionRef)?.validate()
    // await unref(promotionRef)?.validate()
    // await unref(vipDiscountsRef)?.validate()
    // await unref(brokerageRef)?.validate()

    await unref(otherRef)?.validate()
    // 深拷贝一份, 这样最终 server 端不满足，不需要影响原始数据
    const deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu
    // 固定运费价格元转分
    deepCopyFormData.freight = convertToInteger(deepCopyFormData.freight)

    deepCopyFormData.skus!.forEach((item) => {
      // 给sku 商品名称赋值
      item.spuName = deepCopyFormData.spuName
      // sku相关价格元转分
      item.price = convertToInteger(item.price)
      item.marketPrice = convertToInteger(item.marketPrice)
      item.costPrice = convertToInteger(item.costPrice)
      item.lowPrice = convertToInteger(item.lowPrice)

      // 给sku 库存赋值
      if (item.stock == undefined) {
        item.stock = null
      }
    })
    // 处理轮播图列表
    const newSliderPicUrls: any[] = []
    deepCopyFormData.sliderPicUrls!.forEach((item: any) => {
      // 如果是前端选的图
      typeof item === 'object' ? newSliderPicUrls.push(item.url) : newSliderPicUrls.push(item)
    })
    deepCopyFormData.sliderPicUrls = newSliderPicUrls
    // 校验都通过后提交表单
    const data = deepCopyFormData as ProductSpuApi.Spu
    const spuId = params.spuId as unknown as number
    if (!spuId) {
      await ProductSpuApi.createSpu(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductSpuApi.updateSpu(data)
      message.success(t('common.updateSuccess'))
    }
    close()
  } finally {
    formLoading.value = false
  }
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'ProductSpu' })
}

/** 初始化 */
onMounted(async () => {
  await getDetail()
})
</script>
